package com.g2.rpc.remoting.netty;

import com.g2.rpc.remoting.Client;
import com.g2.rpc.remoting.Codec;
import com.g2.rpc.remoting.Handler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.URI;

/**
 * 描述:
 * ${DESCRIPTION}
 *
 * @author lingjiu.kong
 * @version 1.0
 * @date 2021-03-09 23:07
 */
public class NettyClient implements Client {

    Channel channel;


    @Override
    public void connect(URI uri, Codec codec, Handler handler) {
        try {
            NioEventLoopGroup group = new NioEventLoopGroup();
            Bootstrap bootstrap = new Bootstrap();
            // 指定事件循环组
            bootstrap.group(group)
                    // 指定所使用的nio传输channel
                    .channel(NioSocketChannel.class)
                    // 添加一个handler
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new NettyCodec(codec.createInstance()));
                            ch.pipeline().addLast(new NettyHandler(handler));
                        }
                    });
            // 同步-- 创建连接
            ChannelFuture channelFuture = bootstrap.connect(uri.getHost(), uri.getPort()).sync();
            channel = channelFuture.channel();

            // 优雅停机 -- kill pid -- 响应退出信号
            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            }));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void send(byte[] bytes) {
        channel.writeAndFlush(bytes);
    }

}
